package com.centling.smartSealForPhone.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.bean.DetailBean;
import com.centling.smartSealForPhone.bean.LoginBean;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.db.DbControl;
import com.centling.smartSealForPhone.service.UploadImageService;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.example.localalbum.common.ImageUtils;
import com.example.localalbum.common.LocalImageHelper;
import com.example.localalbum.ui.ImageScrollView;
import com.example.localalbum.ui.LocalAlbum;
import com.example.localalbum.ui.UrlImageScrollView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class ReviewUploadActivity
        extends TitleBarActivity {

    private TextView tvFailedPic;

    private UrlImageScrollView failedImageScrollView;
    private List<String> urlList = new ArrayList<>();
    private List<String> nameList = new ArrayList<>();
    private String applyId;
    private String latestReviewRecordId;
    private String reviewPicIds;

    private int uploadNum;
    private TextView tvNum;
    private ImageScrollView uploadImageScrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_review_upload);

        setTitleBarText("补拍照片");

        initView();

        sendRequest();
    }

    private void initView() {

        TextView tvSubmit = (TextView) findViewById(R.id.tv_review_upload_submit);
        if (tvSubmit != null) {
            tvSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tryToSubmit();
                }
            });
        }

        tvFailedPic = (TextView) findViewById(R.id.tv_review_upload_failed_pic);
        failedImageScrollView = (UrlImageScrollView) findViewById(R.id.url_sv_review_upload_failed);

        tvNum = (TextView) findViewById(R.id.tv_review_upload_num);
        uploadImageScrollView = (ImageScrollView) findViewById(R.id.isv_review_upload_pics);
        uploadImageScrollView.setOnDeleteListener(new ImageScrollView.OnDeleteListener() {
            @Override
            public void onDelete(final int pos) {
                new AlertDialog.Builder(mContext).setTitle("删除图片").setMessage("删除这张图片以重新添加")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                uploadImageScrollView.getFiles().remove(pos);
                                uploadImageScrollView.getAdapter().notifyDataSetChanged();
                                LocalImageHelper.getInstance().setCurrentSize(
                                        uploadImageScrollView.getFiles().size());
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
            }
        });
        uploadImageScrollView.setOnAddListener(new ImageScrollView.OnAddListener() {
            @Override
            public void onClick() {
                LocalImageHelper.getInstance().getCheckedItems().clear();
                LocalImageHelper.getInstance().setCurrentSize(
                        uploadImageScrollView.getFiles().size());
                Intent intent = new Intent(ReviewUploadActivity.this, LocalAlbum.class);
                startActivityForResult(intent, ImageUtils.REQUEST_CODE_GET_IMAGE_BY_CROP);
            }
        });
    }

    private void tryToSubmit() {
        if (reviewPicIds == null) {
            return;
        }
        if (uploadNum != uploadImageScrollView.getFiles().size()) {
            ShowToast.shortTime("请上传 " + uploadNum + " 张图片！");
            return;
        }
        sendUploadRequest();
    }

    private void sendRequest() {
        mProcessDialog.setTitle("正在拉取补拍信息").showNormal();
        getEnqueue(String.format(Locale.CHINA, UrlConstants.DETAIL_NEW,
                getIntent().getStringExtra("sealApplyId")), new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                mProcessDialog.dismiss();

                DetailBean bean = new Gson().fromJson(json, DetailBean.class);
                applyId = bean.getSealApplyId();
                latestReviewRecordId = bean.getLatestReviewRecordId();
                reviewPicIds = bean.getReshootRecordIds();
                LocalImageHelper.getInstance().setTotalSize(reviewPicIds.split(",").length);
                tvNum.setText(String.valueOf(reviewPicIds.split(",").length));
                uploadNum = reviewPicIds.split(",").length;

                String[] pics = bean.getPics().split("[,|]");
                if (!TextUtils.isEmpty(bean.getPics()) && pics.length > 0) {
                    for (int i = 0; i < pics.length; i += 2) {
                        urlList.add(pics[i]);
                    }

                    for (int i = 1; i < pics.length; i += 2) {
                        nameList.add(pics[i]);
                    }

                    failedImageScrollView.addFiles(urlList, nameList);
                } else {
                    tvFailedPic.setVisibility(View.GONE);
                    failedImageScrollView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(String reason) {
                mProcessDialog.dismiss();
                ShowToast.shortTime(reason);
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ImageUtils.REQUEST_CODE_GET_IMAGE_BY_CROP) {
            if (LocalImageHelper.getInstance().isResultOk()) {
                LocalImageHelper.getInstance().setResultOk(false);
                List<LocalImageHelper.LocalFile> localFiles = LocalImageHelper.getInstance()
                        .getCheckedItems();
                uploadImageScrollView.addFiles(localFiles);
            }
        }
    }

    private void sendUploadRequest() {
        String url = "/api/v1/sealApply/" + applyId + "/" + latestReviewRecordId + "/reshoot";
        Map<String, String> params = new HashMap<>();
        params.put("picCount", String.valueOf(uploadImageScrollView.getFiles().size()));
        mProcessDialog.setTitle("正在提交补拍信息").showNormal();
        postJsonEnqueue(url, params, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                mProcessDialog.dismiss();

                String[] ids = reviewPicIds.split(",");
                List<String> idList = new ArrayList<>();
                Collections.addAll(idList, ids);
                List<LocalImageHelper.LocalFile> files = uploadImageScrollView.getFiles();
                LoginBean bean = new Gson().fromJson(SPUtil.getString(SPConstants.LOGIN_JSON),
                        LoginBean.class);
                DbControl.getInstance().insertData("3", latestReviewRecordId,
                        bean.getUserLogin().getId() + "", idList, files);

                ConnectivityManager connectMgr = (ConnectivityManager) mContext.getSystemService(
                        Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = connectMgr.getActiveNetworkInfo();

                if (info != null) {
                    if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                        mContext.startService(new Intent(mContext, UploadImageService.class));
                        mActivity.finish();
                    } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                        ShowDialog.showSelectDialog(mContext, "警告", "您当前正在使用移动网络，将会产生大量流量",
                                "推荐在WIFI下上传", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        mContext.startService(
                                                new Intent(mContext, UploadImageService.class));
                                        mActivity.finish();
                                    }
                                }, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        mActivity.finish();
                                    }
                                });
                    }
                }
            }

            @Override
            public void onFailed(String reason) {
                mProcessDialog.dismiss();
                ShowToast.shortTime(reason);
            }
        });
    }
}
